package com.cloud.service.impl;

import com.cloud.dto.InventoryResult;
import com.cloud.service.ProductService;
import com.cloud.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private ProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lock() {

        String[] productIds = new String[]{"a", "b", "c"};
        // 创建 CompletableFuture 列表
        CompletableFuture<InventoryResult>[] futures = new CompletableFuture[productIds.length];
        for (int i = 0; i < productIds.length; i++) {
            String productId = productIds[i];
            futures[i] = CompletableFuture.supplyAsync(() -> {
                // 调用锁库存操作，返回子线程的结果
                return productService.lock(productId);
            });
        }

        // 等待所有异步操作完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures);

        // 等待所有子线程完成
        allFutures.join();  // 使用 join 阻塞主线程，直到所有子线程完成

        // 获取所有子线程的返回值
        InventoryResult[] results = new InventoryResult[futures.length];
        for (int i = 0; i < futures.length; i++) {
            results[i] = futures[i].join(); // 获取每个子线程的返回值
        }

        String message = "";
        // 检查是否有异常
        for (InventoryResult result : results) {
            if ("FAILED".equals(result.getStatus())) {
                message += result.getMessage();
            }
        }

        // 如果所有操作成功，提交事务,否则进行补偿
        System.out.println("All inventory locked successfully:" + message);
    }
}
